﻿using System;
using System.Configuration;
using System.Text;
using System.Windows.Forms;
using FunctionalCLR.Core;

namespace Zove.Desktop {
    public partial class FunctionalCLRPreferences : UserControl {

        public FunctionalCLRPreferences() {
            InitializeComponent();
            Init();
        }

        public void Init() {
            this.tbPrecision.Text = Utils.Precision.ToString();

            string[] lines = System.IO.File.ReadAllLines(
                Utils.ConstantFile, Encoding.UTF8);
            foreach (string ln in lines) {
                string[] p = ln.Split('=');
                gvConstants.Rows.Add(p[0], p[1]);
            }

            string[] classPath = Utils.FunctionPath.Split(';');
            foreach (string cp in classPath) {
                this.gvFunctionLibraries.Rows.Add(cp);
            }
        }

        public void ApplySettings() {
            if (Convert.ToInt32(
                this.tbPrecision.Text) < 0) {
                MessageBox.Show("Precision cannot be negatvie.");
                return;
            }

            ConfigurationManager.AppSettings["precision"] 
                = this.tbPrecision.Text;

            StringBuilder path = new StringBuilder();

            foreach (DataGridViewRow r in this.gvFunctionLibraries.Rows) {
                path.Append(r.Cells["ColLibraryPath"].Value).Append(";");
            }
            Utils.ModelPath = path.ToString();

            path = new StringBuilder();
            foreach (DataGridViewRow r in gvConstants.Rows) {
                if (r.Cells["colName"].Value == null) {
                    continue;
                }

                path.AppendLine(r.Cells["colName"].Value + "=" + r.Cells["colValue"].Value);
            }
            System.IO.File.WriteAllText(Utils.ConstantFile, path.ToString());

            path = new StringBuilder();
            foreach (DataGridViewRow r in this.gvFunctionLibraries.Rows) {
                if (r.Cells["ColLibraryName"].Value == null) {
                    continue;
                }

                path.AppendLine(r.Cells["ColLibraryPath"].Value.ToString()).Append(";");
            }
            path.Remove(path.Length - 1, 1);
            Utils.FunctionPath = path.ToString();
        }
    }
}
